package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFVilleCRUD extends javax.swing.JInternalFrame {

    private Connection icn;
    private DefaultTableModel idtm;
    private Map<String, String> imapDepartements;

    /**
     * Creates new form JIFVillesCRUD
     */
    public JIFVilleCRUD() {
        initComponents();

        setTitle("CRUD Villes");

        try {
            // --- Connexion
//            Class.forName("org.gjt.mm.mysql.Driver");
//            String lsDSN = "jdbc:mysql://127.0.0.1:3306/cinescope2014";
//            icn = DriverManager.getConnection(lsDSN, "root", "");

            icn = Globale.getConnexion();
            idtm = (DefaultTableModel) jTableVilles.getModel();

            String lsSQL;
            PreparedStatement lpst;
            ResultSet lrs;

            lsSQL = "SELECT v.id_ville, v.cp, v.nom_ville, v.id_departement, d.nom_departement FROM ville v INNER JOIN departement d ON v.id_departement = d.id_departement ORDER BY nom_ville";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();

            Object[] tLigne;

            while (lrs.next()) {
                tLigne = new Object[4];

                tLigne[0] = lrs.getString(1);
                tLigne[1] = lrs.getString(2);
                tLigne[2] = lrs.getString(3);
                tLigne[3] = lrs.getString(5);

                idtm.addRow(tLigne);
            }

            lrs.close();
            lpst.close();

            // Les departements
            imapDepartements = new HashMap<>();
            lsSQL = "SELECT id_departement, code_departement, nom_departement FROM departement ORDER BY code_departement";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapDepartements.put(lrs.getString(3), lrs.getString(1));
                jComboBoxDepartements.addItem(lrs.getString(3));
            }
            lrs.close();
            lpst.close();

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException ex) {
            jLabelMessage.setText(ex.getMessage());
        }

        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableVilles = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabelMessage = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldCP = new javax.swing.JTextField();
        jTextFieldNom = new javax.swing.JTextField();
        jComboBoxDepartements = new javax.swing.JComboBox();
        jButtonAjouter = new javax.swing.JButton();
        jButtonSupprimer = new javax.swing.JButton();
        jButtonModifier = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabelID = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jTableVilles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "CP", "Nom", "Département"
            }
        ));
        jTableVilles.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableVillesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableVilles);

        jLabel1.setText("CP");

        jLabel2.setText("Nom");

        jLabelMessage.setText("Message");

        jLabel6.setText("Département");

        jTextFieldCP.setText("94000");

        jTextFieldNom.setText("Créteil");

        jButtonAjouter.setText("Ajouter");
        jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterActionPerformed(evt);
            }
        });

        jButtonSupprimer.setText("Supprimer");
        jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerActionPerformed(evt);
            }
        });

        jButtonModifier.setText("Modifier");
        jButtonModifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifierActionPerformed(evt);
            }
        });

        jLabel5.setText("ID");

        jLabelID.setForeground(new java.awt.Color(255, 0, 51));
        jLabelID.setText("ID");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonAjouter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonModifier)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonSupprimer))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5))
                        .addGap(52, 52, 52)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldCP, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldNom, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                            .addComponent(jComboBoxDepartements, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabelID, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabelID))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldCP, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxDepartements, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAjouter)
                    .addComponent(jButtonSupprimer)
                    .addComponent(jButtonModifier))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelMessage)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        //
//        try {
//            icn.close();
//        } catch (SQLException e) {
//            System.err.println(e.getMessage());
//        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
        //
        try {
            String lsSQL;
            lsSQL = "INSERT INTO ville(cp, nom_ville, id_departement) VALUES(?,?,?)";
            PreparedStatement lpst = icn.prepareStatement(lsSQL);

            lpst.setString(1, jTextFieldCP.getText());
            lpst.setString(2, jTextFieldNom.getText());
            lpst.setString(3, imapDepartements.get(jComboBoxDepartements.getSelectedItem().toString()));
//            System.out.println(jComboBoxDepartements.getSelectedItem().toString());
            lpst.executeUpdate();
            icn.commit();
            lpst.close();

            // Mise a jour de la jTable via le DTM
            String[] tLigne = new String[4];
            tLigne[0] = "";
            tLigne[1] = jTextFieldCP.getText();
            tLigne[2] = jTextFieldNom.getText();
            tLigne[3] = jComboBoxDepartements.getSelectedItem().toString();
            idtm.addRow(tLigne);

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException e) {
            jLabelMessage.setText("KO !!!!");
            System.out.println(e.getMessage());
        }
    }//GEN-LAST:event_jButtonAjouterActionPerformed

    private void jTableVillesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableVillesMouseClicked
        //
        int liLigne = jTableVilles.getSelectedRow();

        jLabelID.setText(jTableVilles.getValueAt(liLigne, 0).toString());
        jTextFieldCP.setText(jTableVilles.getValueAt(liLigne, 1).toString());
        jTextFieldNom.setText(jTableVilles.getValueAt(liLigne, 2).toString());
        jComboBoxDepartements.setSelectedItem(jTableVilles.getValueAt(liLigne, 3).toString());
    }//GEN-LAST:event_jTableVillesMouseClicked

    private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
        //
        if (jTableVilles.getSelectedRow() == -1) {
            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
        } else {
            if (jLabelID.getText().equals("")) {
                idtm.removeRow(jTableVilles.getSelectedRow());
                jLabelMessage.setText("");
            } else {
                try {
                    String lsSQL;
                    lsSQL = "DELETE FROM ville WHERE id_ville=?";
                    PreparedStatement lpst = icn.prepareStatement(lsSQL);

                    lpst.setString(1, jLabelID.getText());

                    lpst.executeUpdate();
                    icn.commit();
                    lpst.close();

                    // Suppression dans la jTable via le DefalutTableModel
                    idtm.removeRow(jTableVilles.getSelectedRow());

                    jLabelMessage.setText("Okay !!!");

                } catch (SQLException e) {
                    jLabelMessage.setText("KO !!!!");
                    System.out.println(e.getMessage());
                }
            }
        }
    }//GEN-LAST:event_jButtonSupprimerActionPerformed

    private void jButtonModifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifierActionPerformed
        // 
        int liLigne = jTableVilles.getSelectedRow();
        if (liLigne == -1) {
            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
        } else {

            try {
                String lsSQL;
                lsSQL = "UPDATE ville SET cp=?, nom_ville=?, id_departement=? WHERE id_ville=?";
                PreparedStatement lpst = icn.prepareStatement(lsSQL);

                lpst.setString(1, jTextFieldCP.getText());
                lpst.setString(2, jTextFieldNom.getText());
                lpst.setString(3, imapDepartements.get(jComboBoxDepartements.getSelectedItem().toString()));
                lpst.setString(4, jLabelID.getText());

                lpst.executeUpdate();
                icn.commit();
                lpst.close();

                // Modification dans la jTable
//                jTableVilles.setValueAt(jTextFieldCP.getText(), liLigne, 1);
//                jTableVilles.setValueAt(jTextFieldNom.getText(), liLigne, 2);
//                jTableVilles.setValueAt(jComboBoxDepartements.getSelectedItem(), liLigne, 3);
                idtm.setValueAt(jTextFieldCP.getText(), liLigne, 1);
                idtm.setValueAt(jTextFieldNom.getText(), liLigne, 2);
                idtm.setValueAt(jComboBoxDepartements.getSelectedItem(), liLigne, 3);

                jLabelMessage.setText("Okay !!!");

            } catch (SQLException e) {
                jLabelMessage.setText("KO !!!!");
                System.out.println(e.getMessage());
            }

        }
    }//GEN-LAST:event_jButtonModifierActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAjouter;
    private javax.swing.JButton jButtonModifier;
    private javax.swing.JButton jButtonSupprimer;
    private javax.swing.JComboBox jComboBoxDepartements;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelID;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableVilles;
    private javax.swing.JTextField jTextFieldCP;
    private javax.swing.JTextField jTextFieldNom;
    // End of variables declaration//GEN-END:variables
}
